<?php

# error_reporting(0);
/*
 * Copyright (C) 2014 koodo@qq.com.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

/**
 * Dao模块，采用PDO
 */
class Db extends Model {

    // dsn
    private $dsn = "mysql:host=localhost;dbname=test";
    // db
    private $db;
    // 单例 todo
    protected static $_instance = NULL;
    // memcached
    public $memcached = false;
    // single instance
    private static $instance = false;
    // db swcache
    public $prevDb = null;

    public static function get_instance() {
        if (!self::$instance) {
            $instance = new Db();
        }
        return $instance;
    }

    /**
     * 
     * @global type $config
     */
    public function __construct($dbname = false) {
        global $config;
        parent::__construct();
        $this->initMemcache($config);
        if ($dbname) {
            $config->db['db'] = $dbname;
        }
        $this->dsn = sprintf("mysql:host=%s;dbname=%s", $config->db['host'], $config->db['db']);
        $this->db = new PDO($this->dsn, $config->db['user'], $config->db['pass']);
        $this->db->exec("SET NAMES 'UTF8'");
    }

    /**
     * @param type $statement
     * @param type $mcache
     * @param type $fetchStyle
     * @return type
     */
    public function query($statement, $mcache = false, $fetchStyle = PDO::FETCH_ASSOC) {
        if (preg_match("/INSERT/is", $statement)) {
            // INSERT
            $this->db->exec($statement);
            $result = $this->db->lastInsertId();
        } else if (preg_match("/UPDATE|DELETE|REPLACE/s", $statement)) {
            // UPDATE|DELETE=
            $result = $this->db->exec($statement);
        } else {
            if ($this->memcached !== false && $mcache) {
                /**
                 * allow memcached <default>
                 */
                $sHash = md5($statement . APPID);
                $mca = $this->memcached->get($sHash);
                if ($mca !== false) {
                    return $mca;
                } else {
                    // SELECT
                    $query = $this->db->prepare($statement);
                    $query->execute();
                    $result = $query->fetchAll($fetchStyle);
                    $this->memcached->set($sHash, $result, MEMCACHE_COMPRESSED, 50);
                }
            } else {
                /**
                 * not allow memcached <sf>
                 */
                $query = $this->db->prepare($statement);
                $query->execute();
                $result = $query->fetchAll($fetchStyle);
            }
        }
        return $result;
    }

    /**
     * 查询一个数据
     * @param type $SQL
     * @return type
     */
    public function getOne($SQL){
        $ret = $this->query($SQL);
        return $ret[0][0];
    }
    
    /**
     * 
     * @param type $statement
     * @return type
     */
    public function exec($statement) {
        return $this->db->exec($statement);
    }

    /**
     * 
     * @param type $config
     * @return boolean
     */
    private function initMemcache($config) {
        if (class_exists('Memcache')) {
            $memcache = new Memcache;
            if ($memcache->connect($config->memcached['host'], $config->memcached['port'])) {
                $this->memcached = $memcache;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 
     * @param type $statement
     * @return type
     */
    public function getSHash($statement) {
        return md5($statement . APPID);
    }

}
